import React, { Component } from 'react'
import { messages } from "share/common";
import { Form, Modal, Input, Checkbox, Switch, message } from 'antd'
import errorMessage from 'share/errorMessage'
import Condition from 'components/condition'
import QuickReply from 'components/template/quick-reply'
import financeAuditService from '../finance-audit.service'
import 'styles/financial-management/new-finance-audit/components/audit-notice-modal.scss'

const FormItem = Form.Item;
const { TextArea } = Input;
const { If } = Condition;

@Form.create()
class AuditNoticeModal extends Component {

  state = {
    loading: false,
    hangUpOpen: false,
    retainLabel: false, //是否保留暂挂标签
  };

  localStoryHangupKey = {
    1002: 'expense-audit-notice-hangup',
    3001: 'borrow-audit-notice-hangup',
    5001: 'expense-bag-audit-notice-hangup'
  };

  localStoryHangupTagKey = {
    1002: 'expense-retain-hangup-tag',
    3001: 'borrow-retain-hangup-tag',
    5001: 'expense-bag-retain-hangup-tag'
  };

  componentDidMount() {
    const { entityType } = this.props;
    this.setState({
      hangUpOpen: localStorage.getItem(this.localStoryHangupKey[entityType]) === 'true',
      retainLabel: localStorage.getItem(this.localStoryHangupTagKey[entityType]) === 'true'
    });
  }

  componentWillReceiveProps(nextProps) {
    const { entityType } = this.props;
    if (nextProps.visible && !this.props.visible) {
      this.setState({ hangUpOpen: localStorage.getItem(this.localStoryHangupKey[entityType]) === 'true' });
      this.getNoticeInfo(nextProps);
    }
  }

  getNoticeInfo = props => {
    const { setFieldsValue } = this.props.form;
    const { entityOID, reason, entityType } = props;
    [1002, 5001].includes(entityType) && financeAuditService.getNoticeInfo(entityOID, entityType).then(res => {
      let notice = reason ? `${reason || ''}\r\n${res.data}` : res.data;
      setFieldsValue({ notice });
    })
  };

  afterSelectTag = creditEvent => {
    const { honestEvent } = this.state;
    this.reasonInput.focus();
    honestEvent && this.setState({ honestEvent: creditEvent || [] });
  };

  handleNotice = () => {
    const { entityOID, entityType } = this.props;
    const { hangUpOpen, retainLabel } = this.state;
    this.props.form.validateFields((err, values) => {
      if (!err) {
        let params = {
          entityType,
          entityOID,
          notice: values.notice,
          pend: hangUpOpen,
          retainLabel
        };
        if (entityType === 5001) {
          params = {
            expenseReportBagCode: entityOID,
            notice: values.notice,
            pend: hangUpOpen,
            retainLabel
          };
        }
        this.setState({ loading: true });
        financeAuditService.noticeApplication(params, entityType).then(() => {
          let successMessage = hangUpOpen ? messages('expense-14.key43')/*已通知并暂挂单据*/ :
            messages('expense-14.key44')/*已通知*/;
          message.success(successMessage);
          this.setState({ loading: false });
          this.props.close(true);
        }).catch(e => {
          this.setState({ loading: false });
          errorMessage(e.response);
        })
      }
    });
  };

  handleHangUp = value => {
    const { entityType } = this.props;
    this.setState({ hangUpOpen: value });
    localStorage.setItem(this.localStoryHangupKey[entityType], value);
  };

  changeHangUpTag = e => {
    const { entityType } = this.props;
    this.setState({ retainLabel: e.target.checked });
    localStorage.setItem(this.localStoryHangupTagKey[entityType], e.target.checked);
  };

  render() {
    const { visible, reason, form: { getFieldDecorator } } = this.props;
    const { loading, hangUpOpen, retainLabel } = this.state;
    return (
      <Modal
        visible={visible}
        title={messages('expense-14.key45')/*通知/暂挂单据*/}
        className="audit-notice-modal"
        confirmLoading={loading}
        onOk={this.handleNotice}
        onCancel={() => this.props.close()}
      >
        <div className="audit-notice-modal-title">{messages('expense-14.key46')/*标题：财务通知*/}</div>
        <div>{messages('expense-14.key47')/*正文*/}：</div>
        <FormItem>
          {getFieldDecorator('notice', {
            rules: [{
              required: true,
              message: messages('expense-14.key48')/*请输入通知内容*/
            }, {
              max: 2000,
              message: messages('common.max.characters.length',{arg1: 2000})/*最多输入{arg1}个字符*/
            }],
            initialValue: reason
          })(
            <QuickReply params={{ audit: true }}>
              <TextArea
                rows={4}
                style={{ resize: 'none' }}
                placeholder={messages('expense-14.key48')/*请输入通知内容*/}
              />
            </QuickReply>
          )}
        </FormItem>
        <div className="audit-notice-modal-switch">
          <Switch
            checked={hangUpOpen}
            onChange={this.handleHangUp}
          />
          {messages('expense-14.key49')/*我要暂挂*/}
        </div>
        <If value={hangUpOpen}>
          <Checkbox
            checked={retainLabel}
            className="audit-notice-modal-checkbox"
            onChange={this.changeHangUpTag}
          >
            {messages('expense-14.key34')/*审核通过后，不清除暂挂标签*/}
          </Checkbox>
        </If>
      </Modal>
    )
  }
}

AuditNoticeModal.propTypes = {
  visible: React.PropTypes.bool,
  entityOID: React.PropTypes.string,
  entityType: React.PropTypes.number,
  reason: React.PropTypes.string,
  close: React.PropTypes.func,
};

export default AuditNoticeModal;
